import React, { useEffect, useState, useRef,useLayoutEffect} from 'react';
import './ChatLog.less';
import { Input, Icon, Tabs,Avatar,Badge,Spin,Button,Popover,DatePicker,ConfigProvider  } from 'antd';
import SvgIcon from '../svgIcon/SvgIcon';
import imsdk from '../../net/IMSDK';
import MessageItemView from '../../component/messageItem/MessageItem';
import ChatStore from '../../store/ChatStore';
import { GroupMemRole } from '../../interface/IGroup';
import { AvatorWithPhoto } from "../avatorWithPhoto/AvatorWithPhoto";
import {formatTimes} from '../../utils/msgtimeUtils';
import MainStore from '../../store/MainStore';
import message from "antd/es/message";
import RcViewer from "@hanyk/rc-viewer";
import Utils from "../../utils/utils";
import zhCN from 'antd/es/locale/zh_CN';
 
import moment from 'moment'
// 一定要用这个路径，否则不生效
import 'moment/locale/zh-cn'
// 日期选择器中文化
moment.locale('zh-cn')


import systemStore from '../../store/SystemStore';

const {RangePicker} = DatePicker;


interface ChatLogProps {
  isOpen: boolean;
  currentChat: any;
  // isOpen: boolean;
  // onClose: () => void;
  // children: React.ReactNode;
}

export default function ChatLog(props: ChatLogProps) {
  const [searchTxt, setSearchTxt] = useState('');
  let submitTxt = ''
  const [msgList,setMsgList] = useState([]);
  const listRef = useRef<HTMLDivElement | null>(null);
  const [msgListShow,setMsgListShow]=useState(false);
  const [loading,setLoading]=useState(false);
  let listRefOnce = true;
  const currentPlayAudioAndVideo = useRef<HTMLMediaElement | null>(null);
  const [listenScroll,setListenScroll]=useState(false);
  let pageIndex = 0;
  let pageSize = 50;
  let activeKey:string|null = null;
  const [showkey,setShowkey] = useState('1')
  const [showdate,setShowdate] =useState(false)
  const [currentDate,setCurrentDate] = useState(null);
  let timeArea=[]


  const changeActiveKey = (key: string) => {
    // console.log("changeActiveKey",key)
    // if (key == '1') {
    //   activeKey = [1,2,8,9];
    // }else if (key=='2') {
    //   activeKey = [2,9];
    // }else if (key=='3') {
    //   activeKey = [9];
    // }else if (key=='4') { //时间这里先不考虑
    //   return 
    // }
    setSearchTxt('')
    submitTxt = ''
    setShowkey(key)
    if (key=='4') {
      //时间待会处理    
      activeKey = null  
      return
    }else{
      activeKey = key
      timeArea=[]
      console.log("选类型时重置时间",timeArea,searchTxt)
      setShowdate(false)
    }

    pageIndex = 0;
    fetchMsg(props.currentChat.type == 1,0)
  }


 
  useEffect(() => {
    submitTxt = searchTxt.trim()
    // console.log('当前 searchTxt', searchTxt);
  }, [searchTxt]);

  const timeAreaChange = (moment,string)=>{
    setSearchTxt('')
    setCurrentDate({
      start:string[0],
      end:string[1]
    })
    setShowdate(false)
    const start = moment[0].startOf('day').unix()
    const end = moment[1].endOf('day').unix()
    timeArea=[start,end]
    console.log("setTimeArea",timeArea,start,end)
    // fetchMsg(props.currentChat.type==1,0,start,end)
    pageIndex = 0;
    fetchMsg(props.currentChat.type==1,0)
  }

  useEffect( () => {
    if (props.isOpen && props.currentChat) {
      setLoading(true)
      setSearchTxt('')
      submitTxt=''
      timeArea=[]
      activeKey = null
      setShowkey('1')
      pageIndex = 0

      console.log("获取聊天记录",props.isOpen,)
      const currentChat = props.currentChat
      if (currentChat.type == 0) {//单聊
        console.log("单聊",currentChat)
        fetchMsg(false)
      }else if (currentChat.type == 1) {//群聊
        console.log("群聊",currentChat)
        fetchMsg(true)
      }else{
        //不存在的情况
      }
      setMsgListShow(false)
      listRefOnce=true
    }
  }, [props.currentChat,props.isOpen]);

  const fetchMsg = async(isGroup: boolean,pageIndex:number=0,startTime:number=0,endTime:number=Date.now()/1000)=>{
      
    console.log("fetchMsg读取setTimeArea",timeArea,searchTxt)
      setLoading(true)
      console.log(timeArea)
      if (timeArea.length==2) {
        startTime = timeArea[0]
        endTime = timeArea[1]
      }
      const fromId = props.currentChat.id;
      let historyRet={
        data:[]
      }
      let arr=[1,2,8,9]
      if (activeKey!=null) {
        if (activeKey=='1') {
          arr=[1,2,8,9]
        }else if (activeKey=='2') {
          arr=[2,9]
        }else if (activeKey=='3') {
          arr=[9]
        }else{   //时间这里先不考虑
          return 
        }
        const re = await imsdk.getHistory1(pageIndex,startTime, Math.floor(endTime), isGroup, fromId, pageSize,arr,submitTxt);
        if (activeKey=='1') {
          historyRet = re
        }else if (activeKey=='2') {
          historyRet.data = re.data.filter(item=>{
            const endstr = item.content.split(".").pop();
            if (picList.includes(endstr)||mp3List.includes(endstr)||mp4List.includes(endstr)){
              return true
            }else{
              return false
            }
          })
        }else if (activeKey=='3') {
          historyRet.data = re.data.filter(item=>{
            const endstr = item.content.split(".").pop();
            if (picList.includes(endstr)||mp3List.includes(endstr)||mp4List.includes(endstr)){
              return false
            }else{
              return true
            }
          })
        }else{   //时间这里先不考虑
          return 
        }
      }else{
        historyRet = await imsdk.getHistory1(pageIndex,startTime, Math.floor(endTime), isGroup, fromId,pageSize, arr,submitTxt);
      }
      console.log("结果",historyRet)
      console.log("参数",0, Math.floor(startTime), Math.floor(endTime), isGroup, fromId, pageSize)
      

      if (pageIndex==0) {
        setMsgList(historyRet.data.reverse());
      }else{
        setMsgList((prevMsgList) => [ ...historyRet.data.reverse(),...prevMsgList]);
      }
      if (historyRet.data.length >=pageSize) {
        setListenScroll(true)
      }else{
        setListenScroll(false)
      }
      setLoading(false)
      console.log("几次？")
      if (!listRefOnce) {
        return
      }
      listRefOnce=false
      console.log("pageIndex",pageIndex)
      if (listRef.current&&pageIndex==0) {
        listRef.current.scrollTop = listRef.current.scrollHeight;
        setMsgListShow(true);
      }else{

      }
      
  }

  const getMessageCard = (msgitem) => {
    const { content, objectId } = msgitem;
    return (
      <div
        className="card-mes"
        onClick={() => {
          showuserInfo(true, objectId ? objectId : "0")
        }}
      >
        <div className="top">
          <AvatorWithPhoto type={0} id={objectId ? objectId : "0"} size={40} />
          <span className="name">{content}</span>
        </div>
        <span className="card-title">个人名片</span>
      </div>
    );
  };

  const searchTypes = [
    {
      label: '全部',
      key: '1',
    },
    {
      label: '图片/音频/视频',
      key: '2',
    },
    {
      label: '文件',
      key: '3',
    },
    {
      label: '日期',
      key: '4',
    }
  ];

  const canViewInfo = Boolean(
    ChatStore.currentChatData.role == GroupMemRole.owner || ChatStore.currentChatData.role == GroupMemRole.manage || !ChatStore.currentChatData.allowFriends
  );
  const showuserInfo = (isMyMes: boolean, fromUserId: string) => {
    if (isMyMes || canViewInfo) {
      MainStore.showInfoModal(fromUserId);
    } else {
      message.warn("该群不允许查看群友信息!");
    }
  };

  const renderimg=(msgitem)=>{
    return  <div className='imgbox' onMouseDown={(event)=>{
      if (event.button === 2) {
        console.log("event.button === 2",event.button === 2,event.button)
      }
    }}>
      <RcViewer
        ref={(ref)=>{
          // this.rcviewer=ref
        }}
        options={{
          toolbar: {
            prev: false,
            play: false,
            next: false,
          },
          title: false,
        }}
      >
        <img
          src={msgitem.content}
          alt="图片解析出错"
          className="img-linmit"
        ></img>
      </RcViewer>
      <a href='' onClick={(event)=>{
        console.log(msgitem)
        event.preventDefault();
        const a= document.createElement('a');
        a.href=msgitem.content.replace(/(https?:\/\/)([0-9]+\.[0-9]+:[0-9]+)/, 'https://127.0.0.1:8080');
        a.download=msgitem.fileName;
        a.click();
      }} style={{padding:0,border:0,margin:0}}>
            下载
          </a>
    </div>
  }
  const radioAndAudio = [];

  const handlePlay = (mediaElement: HTMLMediaElement) => {
    if (currentPlayAudioAndVideo.current && currentPlayAudioAndVideo.current !== mediaElement) {
      currentPlayAudioAndVideo.current.pause();
    }
    currentPlayAudioAndVideo.current = mediaElement;
  };

  const rendermp3=(msgitem)=>{
    return <div>
      <audio controls src={msgitem.content} onPlay={(event) => {
        handlePlay(event.target as HTMLMediaElement)
      }}>
        您的浏览器不支持 audio 元素。
      </audio>
    </div>
  }

  const rendermp4=(msgitem)=>{
    return <div>
      <video width="320" height="240" src={msgitem.content} controls onPlay={(event) => {
        handlePlay(event.target as HTMLMediaElement)
      }}>
        您的浏览器不支持 HTML5 video 标签。
      </video>
    </div>
  }

  const renderfileCanpreview=(msgitem)=>{
    let { content,fileSize, fileName } = JSON.parse(msgitem.body);
    fileSize = Utils.formatSizeToUnit(parseFloat(fileSize));
    return (
      <div className="mes-file-wraper">
        <div className='file-btn'>
          {/* 同源才能指定默认文件名,希望长串地址做文件名就直接content */}
          {/* 桌面端和浏览器的策略不同，桌面端要求https协议，浏览器要求http协议 */}
          {/* {桌面端 https://127.0.0.1:8080} */}
          {/* {浏览器端 https://127.0.0.1:8080} */}
          {/* 如需区分煮面段和浏览器端， 用navigator.userAgent识别设备*/}
          {/* 桌面端 /electron/i.test(userAgent.toLowerCase()) */}
          {/* 现在只要桌面端 */}
          <a href={content.replace(/(https?:\/\/)([0-9]+\.[0-9]+\.[0-9]+\.[0-9]+:[0-9]+)/, 'https://127.0.0.1:8080')} download={fileName} target='_blank' style={{padding:0,border:0,margin:0}}>
            下载
          </a>
          <Button type="default" size='small' onClick={()=>{
            window.open(content)
          }}><Icon type="eye"  style={{fontSize: '14px',color: '#4096FF'}}/></Button>
        </div>
        <span className="left">
          <span>{fileName}</span>
          <span>{fileSize}</span>
        </span>
        <span className="right">
          <Icon type="file" />
        </span>
      </div>
    );
  }

  const renderfileNotpreview=(msgitem)=>{
    let { content,fileSize, fileName } = JSON.parse(msgitem.body);
    fileSize = Utils.formatSizeToUnit(parseFloat(fileSize));
    return (
      <div className="mes-file-wraper">
        <div className='file-btn'>
          {/* 同源才能指定默认文件名,希望长串地址做文件名就直接content */}
          {/* 桌面端和浏览器的策略不同，桌面端要求https协议，浏览器要求http协议 */}
          {/* {桌面端 https://127.0.0.1:8080} */}
          {/* {浏览器端 https://127.0.0.1:8080} */}
          {/* 如需区分煮面段和浏览器端， 用navigator.userAgent识别设备*/}
          {/* 桌面端 /electron/i.test(userAgent.toLowerCase()) */}
          {/* 现在只要桌面端 */}
          <a href={content.replace(/(https?:\/\/)([0-9]+\.[0-9]+\.[0-9]+\.[0-9]+:[0-9]+)/, 'https://127.0.0.1:8080')} download={fileName} target='_blank' style={{padding:0,border:0,margin:0}}>
            下载
          </a>
        </div>
        <span className="left">
          <span>{fileName}</span>
          <span>{fileSize}</span>
        </span>
        <span className="right">
          <Icon type="file" />
        </span>
      </div>
    );
  }

  // const showFileType = ["jpg", "png", "gif"];
  const picList = ['jpg','jpeg','png','gif','avif','svg','webp','bmp']
  const mp3List = ['mp3','wav','ogg']
  const mp4List = ['mp4','webm','avi']
  const canPreview = ['txt','pdf','html','css','js']
  //所以不在以上的，不可预览，只能下载本地去查看
  const getMessageFile = (msgitem) => {
    //文件后缀
    const endstr = msgitem.content.split(".").pop();
    if (picList.includes(endstr)) {  //图片
      return renderimg(msgitem)
    }

    if (mp3List.includes(endstr)) {  //音频
      return rendermp3(msgitem)
    }

    if (mp4List.includes(endstr)) {  //音频
      return rendermp4(msgitem)
    }

    if (canPreview.includes(endstr)) {
      return renderfileCanpreview(msgitem)
    }

    //所有其他类型
    return renderfileNotpreview(msgitem)
  };



  const showtypeArr=['1','2','3','4','5','6','7','8','9']

  return (
    <div onMouseDown={(event)=>{
				event.stopPropagation()
    }} className='chatlog'>
      <div className='search-box'>
        <Input
          suffix={
            searchTxt.length > 0 ? (
              <Icon type="close-circle" theme="filled" style={{ color: '#8CA6F5' }} onClick={() => setSearchTxt('')} />
            ) : null
          }
          size="default"
          onFocus={() => {}}
          placeholder="搜索"
          maxLength={30}
          prefix={<SvgIcon size="12" name="search"></SvgIcon>}
          value={searchTxt}
          onChange={(e) => setSearchTxt(e.target.value)}
          className="custom-input1"
          onPressEnter={(e) => {
            timeArea=[]
            activeKey=null
            setShowkey('1')
            pageIndex = 0;
            fetchMsg(props.currentChat.type == 1,0)
          }}
        />
      </div>
      <div className='search-type'>
        <Tabs size='small' className='custom-tabs' tabBarGutter={0} activeKey={showkey} onTabClick={(itemkey)=>{
          if (itemkey=='4') {
            setShowdate(!showdate)
          }
        }} onChange={changeActiveKey}>
          {searchTypes.map(item => (
              <Tabs.TabPane tab={item.label} key={item.key}>
                  {/* <Popover content={<div>123333</div>} title="Title">
                  </Popover> */}
                {/* 这里可以放置每个标签页的内容 */}
              </Tabs.TabPane>
          ))}
          {/* <div className='custom-data-item' onClick={()=>{customActiveKey()}} style={{borderBottom: showdata?'1px solid red':'none'}}>日期</div> */}
        </Tabs>
        <div className='datase'  style={showdate?{visibility:'visible'}:{visibility:'hidden'}}>
          <ConfigProvider locale={zhCN}>
            <RangePicker getCalendarContainer={(triggerNode)=>{return triggerNode.parentElement}} locale={zhCN} style={{}} open={showdate} onPanelChange={()=>{}} onChange={timeAreaChange} />
          </ConfigProvider>
        </div>
      </div>
      {
        currentDate&&<div className='current-date'>
          {`${currentDate.start} 至 ${currentDate.end}`}
        </div>
      }
      {
        !msgListShow&&<div className='loading-spin'>
        <Spin />
      </div>
      }
      <div ref={listRef} onScroll={(event: React.UIEvent<HTMLDivElement>) => {
        if (!listenScroll) {
          return
        }
        const target = event.currentTarget;
        if (target.scrollTop/target.scrollHeight <0.2) {
          pageIndex++
          console.log("pageIndex++",pageIndex)
          fetchMsg(props.currentChat.type==1,pageIndex)
          setListenScroll(false)
        }
      }} className='custom-chat-list' style={{visibility: msgListShow ? 'visible' : 'hidden'}}>
        {
          msgListShow&&msgList.map((item, index) => {
            const content = JSON.parse(item.body);
            console.log(item.contentType,showtypeArr.includes(item.contentType))
            if(!showtypeArr.includes(item.contentType.toString())){

              return <></>
            }
            // console.log("content",content)
            return (
              <div key={item._id} className='custom-chat-item'>
                <div className='msgleft'>
                  {
                    item.direction == 0 
                    ?<AvatorWithPhoto size={40} id={item.sender} type={0} />
                    :<AvatorWithPhoto size={40} id={item.receiver} type={0} />
                  }
                </div>
                <div className='msgright'>
                  <div className='msgright-top'>
                    <div className='msgright-top-left'>{
                    item.direction == 0||( item.direction ==undefined&&item.sender==systemStore.userId )
                    ?<span className='msg-me'>发送</span>
                    :<span className='msg-you'>接收</span>}{content.fromUserName}</div>
                    <div className='msgright-top-right'>{formatTimes(content.timeSend)}</div>
                  </div>
                  <div className='msgright-bottom'>
                    {
                      item.contentType=='1'&& item.content
                    }
                    {
                      item.contentType=='2'&& renderimg(item)
                    }
                    {
                      // item.contentType=='3'&&<div>语言消息(未启用)</div>
                    }
                    {
                      // item.contentType=='4'&&<div>位置消息(未启用)</div>
                    }
                    {
                      // item.contentType=='5'&&<div>gif消息(未启用)</div>
                    }
                    {
                      // item.contentType=='6'&&<div>视频消息 等一下</div>
                    }
                    {
                      // item.contentType=='7'&&<div>音频消息 等一下</div>
                    }
                    {
                      item.contentType=='8'&&<div>
                        {getMessageCard(item)}
                        <div className="message-sendtext-sendtimer">
                          {''}
                        </div>
                      </div>
                    }
                    {
                      item.contentType=='9'&&
                      <div>
                        {getMessageFile(item)}
                        <div className="message-sendtext-sendtimer"></div>
                      </div>
                    }
                    {
                      //  {formatTimes(item.timeSend)}
                      // item.contentType=='202'&&<div>你撤回了一条消息</div>
                    }
                    {
                      // item.contentType=='84'&&<div>震动 等一下</div>
                    }
                    {
                      // item.contentType=='907'&&<div>通知消息 等一下</div>
                    }
                  </div>
                </div>
              </div>
            )
          })
        }
        <div style={{height: '100px',lineHeight: '100px',textAlign: 'center'}}>{loading?<Spin/>:' - 最新 - '}</div>
      </div>
    </div>
  );
}